package com.oa.modules.approvalsec1.controller;

import java.sql.Array;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.oa.common.utils.FileUtil;
import com.oa.modules.approvalsec1.entity.ProcessItemEntity;
import com.oa.modules.approvalsec1.entity.ProjectEntity;
import com.oa.modules.approvalsec1.entity.ProjectFileEntity;
import com.oa.modules.approvalsec1.entity.ProjectScheduleEntity;
import com.oa.modules.approvalsec1.service.*;
import com.oa.modules.sys.controller.AbstractController;
import com.oa.modules.sys.service.SysUserRoleService;
import com.tencentcloudapi.msp.v20180319.models.Project;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.oa.common.utils.PageUtils;
import com.oa.common.utils.R;

/**
 * project表
 *
 * @author yangwenzhi
 * @email 785297226@qq.com
 * @date 2021-12-10 09:24:51
 */
@RestController
@RequestMapping("project")
@Api(tags = "项目表相关接口")
@Log4j2
public class ProjectController extends AbstractController {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProcessItemService processItemService;
    @Autowired
    private ProjectFileService projectFileService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private ProjectScheduleService projectScheduleService;

    /**
     * 列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "列表")
    //    @RequiresPermissions("generator:project:list")
    public R list(@RequestBody Map<String, Object> params) {
        params.put("roleId", params.get("roleId"));
        PageUtils page = projectService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息   根据项目名称或项目赋码查询项目
     */
    @GetMapping("/info")
    @ApiOperation(value = "信息")
    public R info(String coding, Integer roleId) {
        LambdaQueryWrapper<ProjectEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.and(i -> i.like(ProjectEntity::getEntryName, coding).or().eq(ProjectEntity::getCoding, coding));
        if (roleId != null && roleId == 19) {
            lambdaQueryWrapper.eq(ProjectEntity::getIsImportant, 1);
        } else {
            lambdaQueryWrapper.eq(ProjectEntity::getIsImportant, 0);
        }
        List<ProjectEntity> project = projectService.list(lambdaQueryWrapper);
        return R.ok().put("project", project);
    }

    @GetMapping("/getInfo")
    public R webInfo(String id) {
        ProjectEntity entity = projectService.getOne(new UpdateWrapper<ProjectEntity>().eq("id", id));
        return R.ok().put("data", entity);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存")
    public R save(@RequestBody ProjectEntity project) {
        if ((project.getBbld() != null && project.getBbld() == 1)||(project.getGtzz()!=null&&project.getGtzz()==1)) {
            LambdaQueryWrapper<ProjectEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ProjectEntity::getEntryName, project.getEntryName()).eq(ProjectEntity::getBbld, project.getBbld()).eq(ProjectEntity::getGtzz, project.getGtzz());
            ProjectEntity projectEntity = projectService.getOne(lambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(projectEntity)) {
                return R.error("项目已存在");
            }
            // 如果在其他项目里已经存在这个项目就把其他项目的删掉
            ProjectEntity projectOne = projectService.getOne(new QueryWrapper<ProjectEntity>().eq("entry_name", project.getEntryName()).eq("bbld",0).eq("gtzz",0));
            if (projectOne != null) {
                projectService.removeById(projectOne.getId());
            }
        } else {
            QueryWrapper<ProjectEntity> w = new QueryWrapper<ProjectEntity>().eq("entry_name", project.getEntryName());
            ProjectEntity one = projectService.getOne(w);
            if (one != null) {
                return R.error("项目已存在");
            }
        }
        project.setCreateDate(new Date());
        project.setStatus(0);
        project.setCreateOper("1");
        projectService.save(project);
        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(@RequestBody ProjectEntity project) {
        project.setUpdateDate(new Date());
        projectService.updateById(project);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public R delete(@RequestBody Map<String, Object> params) {
        if (!"".equals(params.get("id")) && params.get("id") != null) {
            ProjectEntity project = projectService.getOne(new QueryWrapper<ProjectEntity>().eq("id", params.get("id")));
            if (project != null) {
                //删除项目本体
                projectService.removeById(project.getId());
                System.out.println("删除");
                //删除所有附件
                QueryWrapper<ProjectFileEntity> wrapper = new QueryWrapper<ProjectFileEntity>().eq("project_id", project.getId());
                //删除服务器中的文件
                List<ProjectFileEntity> projectFilelist = projectFileService.list(wrapper);
                if (projectFilelist.size() > 0) {
                    projectFilelist.forEach(item -> {
                        if (!"".equals(item.getUrl()) && item.getUrl() != null) {
                            FileUtil.deleteFile(item.getUrl());
                        }
                    });
                }
                projectFileService.remove(new QueryWrapper<ProjectFileEntity>().eq("project_id", project.getId()));
            }
        }
        return R.ok();
    }

    /***
     * 微信端使用
     * 企业根据项目赋码查询当前流程进度  只有企业使用
     * @param coding
     * @return
     */
    @GetMapping("/getCompanyProject")
    public R getProjectByCoding(String coding) {
        LambdaQueryWrapper<ProjectEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectEntity::getCoding, coding);
        ProjectEntity projectEntity = projectService.getOne(lambdaQueryWrapper);
        if (projectEntity != null) {
            return R.ok().put("project", projectEntity);
        }
        return R.ok().put("project", "输入项目赋码有误请重新输入");
    }

    /***
     * 微信端使用
     * 根据项目id查询当前流程进度
     * @param id
     * @return
     */
    @GetMapping("/getProcess")
    public R getProcess(Integer id) {
        //项目id   节点 id
        ProjectEntity projectEntity = projectService.getById(id);
        //流程id
        Integer processId = projectEntity.getProcessId();
        //获取该流程下的所有节点
        List<ProcessItemEntity> itemList = processItemService.queryAllItem(processId, projectEntity.getId());

        ArrayList<ProcessItemEntity> waitdel = new ArrayList<>();

        for (int i = 0; i < itemList.size(); i++) {

            ProcessItemEntity processItemEntity = itemList.get(i);

            ProjectScheduleEntity scheduleEntity = projectScheduleService.getById(processItemEntity.getScheduleId());
            //不是一级目录
            if (scheduleEntity != null && scheduleEntity.getParentId() != 0) {
                //查询其底下的子流程
                List<ProjectScheduleEntity> childList = projectScheduleService.list(new QueryWrapper<ProjectScheduleEntity>().eq("parent_id", scheduleEntity.getId()));
                //如果他底下有子流程的话
                if (childList != null && childList.size() > 0) {
                    //获取子流程的id列表
                    List<Integer> itemids = childList.stream().map(j -> j.getId()).collect(Collectors.toList());
                    //将流程信息添加到waitdel集合，最后一起删除
                    List<ProcessItemEntity> list = itemList.stream().filter(o -> itemids.contains(o.getScheduleId())).collect(Collectors.toList());
//                    List<ProcessItemEntity> list = processItemService.list(new QueryWrapper<ProcessItemEntity>().eq("process_id",processId).in("schedule_id",itemids));
                    waitdel.addAll(list);
                    //遍历每个子流程
                    for (int jj = 0; jj < list.size(); jj++) {
                        //对子流程进行赋值操作
                        ProcessItemEntity assign = assign(list.get(jj), id);
                        if (assign != null) {
                            list.set(jj, assign);
                        }
                    }
                    //将赋完值的子流程set到上级流程的childList集合里
                    processItemEntity.setChildren(list);

                    //判断父流程状态
                    Integer parentState = 0;
                    //判断parentState=1的情况
                    long reason1 = list.stream().filter(j -> j.getReason() != null && (j.getReason() == 1 || j.getReason() == 2)).count();

                    long statusnow1 = list.stream().filter(j -> j.getStatusNow() == 1).count();

                    long reason4 = list.stream().filter(j -> j.getReason() != null && j.getReason() == 4).count();

                    if (reason1 == list.size() || statusnow1 == list.size() || reason4 == list.size()) {
                        parentState = 1;
                    }
                    for (ProcessItemEntity itemEntity : list) {
                        itemEntity.setParentState(parentState);
                    }


                    //判断子流程的statusnow和reason 对此流程的statusnow和reaosn赋值，只有子流程的statusnow和reason相同的话才会对夫流程的reason和statusnow赋值
                    //获取子流程的id集合
                    List<Integer> collect = list.stream().map(j -> j.getId()).collect(Collectors.toList());
                    //根据子流程的id和项目id查询他们流程的证照信息
                    List<ProjectFileEntity> l = projectFileService.list(new QueryWrapper<ProjectFileEntity>().eq("project_id", id).in("item_id", collect));
                    if (l.size() == itemids.size()) {
                        long reasonIsNull = l.stream().filter(n -> n.getReason() == null).count();
                        if (l != null && l.size() > 0 && reasonIsNull == 0) {
                            //循环遍历获取他的子流程证照信息的reason属性相同的个数
                            long count = l.stream().map(ProjectFileEntity::getReason).distinct().count();
                            //如果count==1的话说明子流程的证照信息reason属性都是相同的
                            if (count == 1) {
                                //将子流程的reason属性赋值给父流程的reason属性
                                if (l.get(0).getReason() == 1 && l.get(0).getReason() == 2) {
                                    processItemEntity.setStatusNow(1);
                                } else {
                                    processItemEntity.setReason(l.get(0).getReason());
                                }
                            } else {
                                long c = l.stream().filter(o -> o.getReason() == 1 || o.getReason() == 2).count();
                                if (c == l.size()) {
                                    processItemEntity.setReason(1);
                                }
                            }
                            //如果子流程其中有一个reason属性为null，说明他们的reason肯定不相同或者都为null就不为父流程的reason赋值
                            //则判断statusnow
                        } else {
                            //同上
                            long c = l.stream().map(ProjectFileEntity::getStatusNow).distinct().count();
                            if (c == 1) {
                                processItemEntity.setStatusNow(l.get(0).getStatusNow());
                            }
                        }
                        itemList.set(i, processItemEntity);
                    }
                } else {
                    ProcessItemEntity assign = assign(itemList.get(i), id);
                    if (assign != null) {
                        itemList.set(i, assign);
                    }
                }
            }
        }

        //删除在外面的二级
        if (waitdel != null && waitdel.size() > 0) {
            for (int i = 0; i < itemList.size(); i++) {
                waitdel.forEach(item -> {
                    itemList.removeIf(e -> e.getId() == item.getId());
                });
            }
        }
        //删除阶段流程
        List<Integer> ids = projectScheduleService.list(new QueryWrapper<ProjectScheduleEntity>().eq("parent_id", 0)).stream().map(e -> e.getId()).collect(Collectors.toList());
        List<ProcessItemEntity> collect = itemList.stream().filter(e -> ids.contains(e.getScheduleId())).collect(Collectors.toList());
        itemList.removeAll(collect);
        return R.ok().put("list", itemList);
    }

    private ProcessItemEntity assign(ProcessItemEntity processItemEntity, Integer projectId) {
        LambdaQueryWrapper<ProjectFileEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProjectFileEntity::getItemId, processItemEntity.getId())
                .eq(ProjectFileEntity::getProjectId, projectId);
        ProjectFileEntity map = projectFileService.getOne(lambdaQueryWrapper);
        if (map == null) {
            return null;
        } else {
            Date completionTime = map.getCompletionTime();
            processItemEntity.setCompletionTime(completionTime);
            processItemEntity.setStatusNow(map.getStatusNow());
        }
        processItemEntity.setReason(map.getReason());
        processItemEntity.setReasonThat(map.getReasonThat());
        return processItemEntity;
    }

    /**
     * 微信端搜索项目 模糊查询
     *
     * @param name
     * @return
     */
    @GetMapping("/getProjectByName")
    public R getProjectByName(String name, String company, Integer roleId) {
        LambdaQueryWrapper<ProjectEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !"".equals(name)) {
            lambdaQueryWrapper.like(ProjectEntity::getEntryName, name).last("limit 5");
        }
        if (company != null && !"".equals(company)) {
            lambdaQueryWrapper.eq(ProjectEntity::getCompany, company);
        }
        if (roleId != null && roleId == 19) {
            lambdaQueryWrapper.eq(ProjectEntity::getIsImportant, 1);
        } else {
            lambdaQueryWrapper.ne(ProjectEntity::getIsImportant, 1);
        }
        List<ProjectEntity> list = projectService.list(lambdaQueryWrapper);
        List<Map<String, Object>> maps = new ArrayList<>();
        for (ProjectEntity projectEntity : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", projectEntity.getId());
            map.put("coding", projectEntity.getCoding());
            map.put("entryName", projectEntity.getEntryName());
            maps.add(map);
        }
        return R.ok().put("project", maps);
    }

    /**
     * 挂图作战列表
     *
     * @param params
     * @return
     */
    @PostMapping("/gtzzList")
    public R gtzzList(@RequestBody Map<String, Object> params) {
        params.put("roleId", params.get("roleId"));
        PageUtils page = projectService.gtzzList(params);
        return R.ok().put("page", page);
    }
}
